﻿using Ma.Bussiness.AttributeExtend;
using Ma.Bussiness.ConfigExtend;
using Ma.Bussiness.ModelExtend;
using System.Data.SqlClient;

namespace Ma.Bussiness.DBExtend.SQLQueryExtend;

public static class ExecuteHelper
{
    /// <summary>
    ///  打开数据库链接，执行完毕后返回结果集
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="sql"></param>
    /// <returns></returns>
    public static List<T> ExecuteReader<T>(string sql) where T : BaseModel
    {
        List<T> list = new List<T>();
        Type type = typeof(T);
        //using (SqlConnection conn = new SqlConnection(StaticField.Connection))
        //{
        //    SqlCommand sqlCommand = new SqlCommand(sql, conn);
        //    conn.Open();
        //    SqlDataReader reader = sqlCommand.ExecuteReader();
        //    while (reader.Read())
        //    {
        //        T t = (T)Activator.CreateInstance(type);
        //        foreach (var prop in type.GetProperties())
        //        {
        //            prop.SetValue(t, reader[prop.GetMappingColumnName()] == DBNull.Value ? null : reader[prop.GetMappingColumnName()]);
        //        }
        //        list.Add(t);
        //    }
        //}

        return Command<List<T>>(sql, sqlCommand => {
            SqlDataReader reader = sqlCommand.ExecuteReader();
            while (reader.Read())
            {
                T t = (T)Activator.CreateInstance(type);
                foreach (var prop in type.GetProperties())
                {
                    prop.SetValue(t, reader[prop.GetMappingColumnName()] == DBNull.Value ? null : reader[prop.GetMappingColumnName()]);
                }
                list.Add(t);
            }
            return list;
        });

    }

    /// <summary>
    /// 通用的动作：创建、打开、释放连接 sqlcommand创建
    /// </summary>
    /// <param name="sql"></param>
    /// <param name="func"></param>
    /// <returns></returns>
    public static T Command<T>(string sql, Func<SqlCommand, T> func)
    {
        using SqlConnection conn = new SqlConnection(StaticField.Connection);
        SqlCommand sqlCommand = new SqlCommand(sql, conn);
        conn.Open();
        return func.Invoke(sqlCommand);
    }
}
